package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(version = "1.0.0")
public class VideoApiImpl implements VideoApi {
    @Autowired
    private IdService idService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_USER_FOLLOW_REDIS_KEY_PREFIX = "USER_FOLLOW_";

    @Override
    public String saveVideo(Video video) {
        try {
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getVideoUrl(), video.getPicUrl())) {
                return null;
            }
            video.setId(ObjectId.get());
            video.setCreated(System.currentTimeMillis());
            video.setVid(idService.createId(IdType.VIDEO));
            mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }
        return null;
    }

    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<Long> vids = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //手动分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');
            //计算分页
            //[0, 10]
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束

            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vidList.size();
        }
        if (CollUtil.isEmpty(vids)) {
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
            return pageInfo;
        }
        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    @Override
    public Video queryVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId), Video.class);
    }

    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        try {
            if (this.isFollowUser(userId, followUserId)) {
                return false;
            }
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            String redisKey = getUserFollowRedisKeyPrefix(userId);
            String hashKey = String.valueOf(followUserId);
            redisTemplate.opsForHash().put(redisKey, hashKey, "1");
            mongoTemplate.save(followUser);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    public Boolean disfollowUser(Long userId, Long disfollowUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, disfollowUserId)) {
            return false;
        }
        try {
            if (this.isFollowUser(userId, disfollowUserId)) {
                String redisKey = getUserFollowRedisKeyPrefix(userId);
                String hashKey = String.valueOf(disfollowUserId);
                redisTemplate.opsForHash().delete(redisKey,hashKey);
            }
            Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(disfollowUserId));
            mongoTemplate.remove(query, FollowUser.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private String getUserFollowRedisKeyPrefix(Long userId) {

        return VIDEO_USER_FOLLOW_REDIS_KEY_PREFIX + userId;
    }

    private boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = getUserFollowRedisKeyPrefix(userId);
        String hashKey = String.valueOf(followUserId);
        Boolean bool = redisTemplate.opsForHash().hasKey(redisKey, hashKey);
        return bool;
    }


}
